<?php
namespace Admin\Controller;

use Common\Lib\User\UserHelper;
use Common\Lib\User\UserInfoException;

/**
 * Class MyController
 * @package Admin\Controller
 */
class MyController extends AbstractController {
    protected $Sex;
    function _initialize() {
        parent::_initialize();
        $this->Sex = array(1=>'男',2=>'女');
    }
    public function index(){
        $ID = session('USER_ID');
        $user = M('User')->where(array('ID'=>$ID))->find();
        $this->assign("User",$user);

        $this->assign("Sex",$this->Sex);
        $this->display();
    }

    public function edit(){
        if(IS_POST){
            $data = $_POST;
            $data['ID'] = session('USER_ID');
            try{
                UserHelper::edit($data);
                $this->success('修改成功');
            }catch (UserInfoException $exception){
                $this->error($exception->getMessage());
            }
        }
    }


    public function resetPassword(){
        if(IS_POST){
            $ID = session('USER_ID');
            $data = M('User')->find($ID);

            if(!empty($_POST['Password'])){
                $data['Password'] = $_POST['Password'];
            }
            try{
                $result = UserHelper::edit($data);
                $this->success('密码修改成功');
            }catch (UserInfoException $exception){
                $this->error($exception->getMessage());
            }
        }else{
            $id = session('USER_ID');
            $user = M('User')->where(array('ID' => $id))->find();
            $this->assign('User',$user);
            $this->display();
        }
    }

    /**
     * 上传用户头像
     */
    public function upload_avatar(){
        $baseImg = $_POST['avatar'];
        $baseImgStr = str_replace(array('data:image/jpeg;base64,','data:image/jpg;base64,','data:image/png;base64,','data:image/gif;base64,'), '', $baseImg);
        $path = './data/upload/avatar/';
        $output_file = session('USER_ID').'.jpg';
        $fullPath = $path.$output_file;
        if(file_put_contents($fullPath, base64_decode($baseImgStr))){
            resizeImage($fullPath,$path.'thumb/'.session('USER_ID').'.jpg');
            $this->success(true);
        }else{
            $this->error('上传头像失败，请检查文件目录是否有写入权限');
        }
    }
}